# -*- coding: utf-8 -*-
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q
from .models import Department
from .serializers import DepartmentSerializer, DepartmentTreeSerializer, DepartmentOptionSerializer
from utils.permissions import AdminPermission


class DepartmentViewSet(ModelViewSet):
    """
    部门管理视图集
    """
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer
    permission_classes = [IsAuthenticated]
    
    def get_permissions(self):
        """根据操作类型设置权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            # 创建、更新、删除操作需要管理员权限
            permission_classes = [IsAuthenticated, AdminPermission]
        else:
            # 查看操作只需要登录
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes]
    
    def get_queryset(self):
        """获取查询集"""
        # 管理员可以看到所有部门，普通用户只能看到激活的部门
        if self.request.user.user_type in ['ADMIN', 'MANAGER']:
            queryset = Department.objects.all()
        else:
            queryset = Department.objects.filter(is_active=True)
        
        # 搜索功能 - 只搜索部门名称
        search = self.request.query_params.get('search', '')
        if search:
            queryset = queryset.filter(name__icontains=search)
        
        return queryset.order_by('name')
    
    def list(self, request, *args, **kwargs):
        """获取部门列表"""
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        
        return Response({
            'status': status.HTTP_200_OK,
            'data': serializer.data,
            'count': len(serializer.data)
        })
    
    def create(self, request, *args, **kwargs):
        """创建部门"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'status': status.HTTP_201_CREATED,
            'data': serializer.data,
            'msg': '部门创建成功，需要管理员激活后才能使用'
        })
    
    def update(self, request, *args, **kwargs):
        """更新部门"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'status': status.HTTP_200_OK,
            'data': serializer.data,
            'msg': '部门更新成功'
        })
    
    def destroy(self, request, *args, **kwargs):
        """删除部门（软删除）"""
        instance = self.get_object()
        
        # 检查是否有子部门
        if instance.children.filter(is_active=True).exists():
            return Response({
                'status': status.HTTP_400_BAD_REQUEST,
                'msg': '该部门下还有子部门，无法删除'
            })
        
        # 检查是否有用户
        if instance.user_set.exists():
            return Response({
                'status': status.HTTP_400_BAD_REQUEST,
                'msg': '该部门下还有用户，无法删除'
            })
        
        # 软删除
        instance.is_active = False
        instance.save()
        
        return Response({
            'status': status.HTTP_200_OK,
            'msg': '部门删除成功'
        })
    
    @action(methods=['get'], detail=False)
    def tree(self, request):
        """获取部门树形结构"""
        # 只获取顶级部门（没有父部门的部门）
        root_departments = self.get_queryset().filter(parent__isnull=True)
        serializer = DepartmentTreeSerializer(root_departments, many=True)
        
        return Response({
            'status': status.HTTP_200_OK,
            'data': serializer.data
        })
    
    @action(methods=['get'], detail=False)
    def options(self, request):
        """获取部门选项列表（用于下拉选择）- 只返回激活的部门"""
        # 强制只返回激活的部门，不管用户权限
        departments = Department.objects.filter(is_active=True).order_by('name')
        serializer = DepartmentOptionSerializer(departments, many=True)
        
        return Response({
            'status': status.HTTP_200_OK,
            'data': serializer.data
        })
    
    @action(methods=['put'], detail=True)
    def activate_department(self, request, pk=None):
        """管理员激活/禁用部门"""
        # 检查权限 - 只有管理员和测试管理员可以激活部门
        if not (request.user.user_type in ['ADMIN', 'MANAGER']):
            return Response({
                'status': status.HTTP_403_FORBIDDEN,
                'msg': '只有管理员和测试管理员可以激活部门'
            })
        
        try:
            department = self.get_object()
        except Department.DoesNotExist:
            return Response({
                'status': status.HTTP_404_NOT_FOUND,
                'msg': '部门不存在'
            })
        
        # 获取激活状态
        is_active = request.data.get('is_active', True)
        
        # 如果要禁用部门，检查是否有用户
        if not is_active and department.user_set.exists():
            return Response({
                'status': status.HTTP_400_BAD_REQUEST,
                'msg': '该部门下还有用户，无法禁用'
            })
        
        # 更新部门状态
        department.is_active = is_active
        department.save()
        
        action_text = '激活' if is_active else '禁用'
        
        # 返回更新后的部门信息
        serializer = self.get_serializer(department)
        return Response({
            'status': status.HTTP_200_OK,
            'data': serializer.data,
            'msg': f'部门{action_text}成功'
        })
    
    @action(methods=['get'], detail=True)
    def users(self, request, pk=None):
        """获取部门下的用户"""
        department = self.get_object()
        users = department.user_set.filter(is_active=True)
        
        # 简单的用户信息序列化
        user_data = []
        for user in users:
            user_data.append({
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'user_type': user.user_type,
                'employee_id': user.employee_id
            })
        
        return Response({
            'status': status.HTTP_200_OK,
            'data': user_data
        })